#ifndef _DISTANCE_H_
#define _DISTANCE_H_
#include <Arduino.h>
class distance_cs
{

private:
    const int trig = 8;
    const int echo = 7;

public:
    float distance = 0;
    float distance_last = 0;
    distance_cs()
    {
        Serial.println("distance ok!");
        pinMode(trig, OUTPUT);
        pinMode(echo, INPUT);
    };
    float get_distance()
    {
        digitalWrite(trig, LOW);
        delayMicroseconds(2);
        digitalWrite(trig, HIGH);
        delayMicroseconds(10); // 产生一个10us的高脉冲去触发SR04
        digitalWrite(trig, LOW);

        int time = pulseIn(echo, HIGH); // 检测脉冲宽度，注意返回值是微秒us
        distance = time / 58.0;         // 计算出距离,输出的距离的单位是厘米cm
        distance = (distance > 0) ? distance : distance_last;
        distance_last = distance;
        return distance;
    };
};
#endif